import { Body, Controller, Delete, Get, Param, Post, Put, Query, UsePipes } from '@nestjs/common';
import { UserService } from './user.service';
import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe';
import {
  CreateUserDto,
  UpdateUserDto,
  ParamDto,
  createUserSchema,
  updateUserSchema,
  paramSchema,
  queryUserSchema,
  QueryUserDto
} from './dto/user.schema';
import { RequiresPermissions } from '../../common/decorators/requires-permissions.decorator';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { ApiBody, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'

@ApiTags('用户模块')
@Controller('users')
export class UserController {
  constructor(private readonly userService: UserService) { }

  @Post()
  @ApiOperation({ summary: '创建用户' })
  @RequiresPermissions('system:user:add')
  @UsePipes(new ZodValidationPipe(createUserSchema))
  create(@Body() createUserDto: CreateUserDto, @CurrentUser() currentUser: any) {
    const userWithCreator = {
      ...createUserDto,
      createBy: currentUser.userName,
    };
    return this.userService.create(userWithCreator);
  }

  @Get()
  @RequiresPermissions('system:user:list')
  @ApiOperation({ summary: '用户列表' })
  findAll(@Query(new ZodValidationPipe(queryUserSchema)) query?: QueryUserDto) {
    return this.userService.findAll(query);
  }

  @Get(':id')
  @RequiresPermissions('system:user:query')
  @ApiOperation({ summary: '根据id获取用户' })
  @ApiParam({
    name: 'id',
    type: 'string',
    description: '用户ID',
    required: true
  })
  @UsePipes(new ZodValidationPipe(paramSchema))
  findOne(@Param() params: ParamDto) {
    return this.userService.findOne(+params.id);
  }

  @Put(':id')
  @RequiresPermissions('system:user:edit')
  @ApiOperation({ summary: '更新用户' })
  @ApiParam({
    name: 'id',
    type: 'string',
    description: '用户ID',
    required: true
  })
  @UsePipes(new ZodValidationPipe(paramSchema))
  update(
    @Param() params: ParamDto,
    @Body(new ZodValidationPipe(updateUserSchema)) updateUserDto: UpdateUserDto,
    @CurrentUser() currentUser: any
  ) {
    const userWithUpdater = {
      ...updateUserDto,
      updateBy: currentUser.userName,
    };
    return this.userService.update(+params.id, userWithUpdater);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除用户' })
  @RequiresPermissions('system:user:remove')
  @ApiParam({
    name: 'id',
    type: 'string',
    description: '用户ID',
    required: true
  })
  @UsePipes(new ZodValidationPipe(paramSchema))
  remove(@Param() params: ParamDto) {
    return this.userService.remove(+params.id);
  }
}